package agents.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ActionPredicate {
	
	public static String parseVariable(String variable){
		if (variable.startsWith("?")) {
			return variable.substring(1);
		} else
			return variable;
	}
	
	public static String parseExpression(String expression) {
		Pattern p = Pattern.compile("[?A-z0-9. ]+[+-/*][ ?A-z0-9.]+");
		Matcher m = p.matcher(expression);
		if(m.matches()){
			Pattern p2 = Pattern.compile("[?A-z0-9]+");
			Matcher m2 = p2.matcher(expression);
			StringBuffer sb = new StringBuffer();
			boolean found = m2.find();
			while(found){
				m2.appendReplacement(sb, parseVariable(m2.group()));
				found = m2.find();
			}
			return sb.toString();
		}
		return parseVariable(expression);
	}
	
	public static String convertTo(String expression, long base){
		Pattern p2 = Pattern.compile("[0-9.]+");
		Matcher m2 = p2.matcher(expression);
		StringBuffer sb = new StringBuffer();
		boolean found = m2.find();
		while(found){
			expression = m2.replaceFirst(convert(m2.group(), base));
			found = m2.find();
		}
		return expression;
	}
	
	public static String convert(String n, long base){
		double f = Float.parseFloat(n);
		return ((long)f*base)+"";
	}
	
	public static String evaluateExpression(String expression){
		Pattern p = Pattern.compile("[-+\\*/]\\([0-9]*,[0-9]*\\)");
		Matcher m = p.matcher(expression);
		if(m.matches()){
			Pattern pn = Pattern.compile("[0-9]+");
			Matcher mn = pn.matcher(expression);
			mn.find();
			long n1 = Long.parseLong(mn.group());
			mn.find();
			long n2 = Long.parseLong(mn.group());
			char op = expression.charAt(0);
			switch(op){
				case '+' : return (n1+n2)+"";
				case '-' : return (n1-n2)+"";
				case '*' : return (n1*n2)+"";
				case '/' : if(n2!=0) return (n1/n2)+""; else return "0";
				default : return "0";
			}
		}
		else{
			return "0";
		}
	}
	
	public static void main(String []arguments){
		String expression = "-(2,2)";
		String res = evaluateExpression(expression);
		System.out.println(res);
		
	}
	
}
